import { Collapse, ConfigProvider, Form } from 'antd'
import { useEffect } from 'react'
import { CaretRightOutlined } from '@ant-design/icons'
import ComponentStyle from './ComponentStyle'
import ItemRender from './components/ItemRender'
import type { ModuleProps } from '@/store/Schema'

const { Panel } = Collapse

function FormRender(props: {
  formPropsConfig: ModuleProps
  defaultProps?: Record<string, any>
  onValuesChange?: (values: Record<string, any>) => void
}) {
  const { formPropsConfig, defaultProps = {}, onValuesChange } = props
  const [form] = Form.useForm()

  useEffect(() => {
    form.resetFields()
    form.setFieldsValue(JSON.parse(JSON.stringify(defaultProps)))
  }, [formPropsConfig, defaultProps])

  return (
    <ConfigProvider theme={{
      token: {
        padding: 0,
        paddingLG: 0,
        paddingSM: 5,
        paddingXS: 5,
        paddingXXS: 0,
      },
    }}>
      <Form
        size="small"
        form={form}
        layout="horizontal"
        labelCol={{ span: 8 }}
        labelAlign="left"
        labelWrap
        colon={false}
        onValuesChange={(r, values) => {
          onValuesChange && onValuesChange(values)
        }}
      >
        {Array.isArray(formPropsConfig)
          ? <Collapse
            size="small"
            defaultActiveKey={(formPropsConfig).map((option, idx) => option.label)}
            bordered={false}
            ghost
            expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
            style={{ background: '#fff', padding: 0 }}
          >
            {
              formPropsConfig.map((option, idx) => {
                const { label, value, configType = 'normal' } = option
                return <Panel header={label} key={String(label)} >
                  <div className='p-l-10px'>
                    {
                      configType !== 'componentStyle'
                        ? Object.entries(value).map(([name, itemValue]) => {
                          return <ItemRender name={name} itemValue={itemValue} />
                        })
                        : <ComponentStyle />
                    }
                  </div>
                </Panel>
              })
            }
          </Collapse>
          : Object.entries(formPropsConfig).map(([name, itemValue]) => {
            return itemValue.configType !== 'componentStyle' ? <ItemRender name={name} itemValue={itemValue} /> : <ComponentStyle />
          })}
      </Form>
    </ConfigProvider>

  )
}

export default FormRender
